package com.lm.scau.mailottodemo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.ref.WeakReference;

import me.drakeet.mailotto.Mail;
import me.drakeet.mailotto.Mailbox;

public class MainActivity extends AppCompatActivity {
    private TextView tvInfo;
    private Handler mHander;
    private Button btnPreload;
    private Button btnNext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvInfo = (TextView) findViewById(R.id.tv_info);
        btnPreload = (Button) findViewById(R.id.btnPreload);
        btnNext = (Button) findViewById(R.id.btnNext);
        btnNext.setOnClickListener(new mClickListener());
        btnPreload.setOnClickListener(new mClickListener());
        mHander = new Handler();
    }

    public static class InnerRunable implements Runnable {
        WeakReference<TextView> textViewWeakReference;
        public InnerRunable(TextView textView) {
            this.textViewWeakReference = new WeakReference<>((TextView) textView);
        }
        @Override
        public void run() {
            if(null!=textViewWeakReference.get()){
                textViewWeakReference.get().setText("模拟线程执行完毕！");
            }
            Mailbox.getInstance().post(new Mail("A mail from MainActivity", TargetActivity.class));
        }
    }

    class mClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btnPreload:
                    tvInfo.setText("模拟8S的线程耗时...");
                    mHander.postDelayed(new InnerRunable(tvInfo), 8 * 1000);
                    break;
                case R.id.btnNext:
                    beginNext();
                    break;
                default:
                    break;
            }
        }
    }

    private void beginNext() {
        Intent intent = new Intent(MainActivity.this, NextActivity.class);
        startActivity(intent);
        Toast.makeText(MainActivity.this, "MainActivity has been destroyed.", Toast.LENGTH_LONG).show();
        this.finish();
    }
}
